
define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util  = require('util');
	var view  = require('@base/view');

	// 处理缩略图
	var imageErrorCbs = {};
	function imageErrorCb(type){
		return function(){
			var img = $(this);
			var src = img.attr('src');
			var url = pubjs.config('default_img/'+type);
			if (src == url) { return false; }
			img.attr('src', url);
		};
	}
	// 提供给图片错误时的回调函数
	// 使用： MVVM中在img标签上加上【ms-on-error="evImageError(this, '类型')"】 属性即可
	//        view_model中加上 【evImageErrorsh:common.onImageError】 属性
	exports.onImageError = function(img, type) {
		imageErrorCb(type).call(img);
	}
	/**
	 * 绑定图片错误, 自动打开对应的系统配置的默认图片地址
	 * @param  {Element} dom  要绑定事件的IMG对象DOM/jQuery
	 * @param  {String}  type 自动覆盖的默认图片类型, 对应config的 default_img/<type>
	 * @return {None}         无返回
	 */
	exports.imageError = function(dom, type){
		var func = imageErrorCbs[type];
		if (!func){
			func = imageErrorCbs[type] = imageErrorCb(type);
		}
		$(dom).bind('error', func);
	}

	// 待加载的图片队列
	var IMAGE_QUEUE = [];
	// 加载中的图片总数
	var IMAGE_LOADING_QUEUE_COUNT = 0;
	// 最大同时加载的图片请求总数,暂时是默认一个
	var IMAGE_LOADING_QUEUE_LIMIT = 3;

	function loadImageSucc(){
		this.linker.attr('src', this.src).trigger('imageLoad');
		this.linker = null;
		IMAGE_LOADING_QUEUE_COUNT--;
		triggerLoadImage();
	}
	function loadImageErr(){
		this.linker.trigger('imageError');
		this.linker = null;
		IMAGE_LOADING_QUEUE_COUNT--;
		triggerLoadImage();
	}
	exports.loadImage = function(type, url, dom){
		// 创建和设置默认图片
		if (!dom){ dom = $('<img />'); }
		dom.attr('src', pubjs.config('default_img/'+type));

		if (url){
			// 加载真实图片
			var image_info = {
				'dom': dom,
				'src': url
			};
			IMAGE_QUEUE.push(image_info);
			triggerLoadImage();
		}else {
			// 无设置图片URL, 异步触发错误事件
			setTimeout(function(){
				dom.trigger('imageError');
			}, 0);
		}
		return dom;
	};

	function triggerLoadImage()
	{
		if (IMAGE_LOADING_QUEUE_COUNT >= IMAGE_LOADING_QUEUE_LIMIT)
		{
			return false;
		}

		var image = IMAGE_QUEUE.shift();
		if (image && image.dom && image.src)
		{
			// 加载真实图片
			var loader = new Image();
			loader.linker = image.dom;
			loader.onload = loadImageSucc;
			loader.onerror = loadImageErr;
			loader.src = image.src;
			IMAGE_LOADING_QUEUE_COUNT++;
		}
	}

	var thumb_builder;
	exports.imageThumb = function(url, width, height){
		// 判断url是否已经有附加参数
		var mark = /\?/;
		if(mark.test(url)){
			return url+'&w='+width+'&h='+height;
		}else{
			if (!thumb_builder){
				thumb_builder = pubjs.config('thumb_script');
			}
			return util.formatIndex(
				thumb_builder,
				url, height, width
			);
		}
	}

	// 批量导出表格数据
	exports.getExportApi = function(grid, ids){
		// 获取当前列表的全部参数
		var param = grid.getParam(true);
		// 要导出记录的id号
		param.ids = ids;

		var type = grid.getConfig('exportParam') || grid.getConfig('gridName');

		var url = '/api/dsp/export/'+type;

		return pubjs.data.resolve(url, param);
	}

	// 搜索结果过滤
	var ResultFilter = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': 'P-overviewCustomerFilter',
				'items': [],
				'title': ''

			});
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var c = this.getConfig();
            if(c.title){
                $('<div class="commonResultFilterTitle">'+ c.title + '</div>').appendTo(this.$el);
            }
			for (var i = 0; i < c.items.length; i++) {
				this.buildOption(c.items[i]);
			}
		},
		buildOption: function(data){
			var dom = $('<span data-id="'+data.value+'" class="option"><i/><label>'+data.text+'</label></span>').appendTo(this.$el);
			this.uiBind(dom, 'click', 'eventButtonClick');
		},
		eventButtonClick: function(ev, el){
			el = $(el);
			el.toggleClass('act');
			var data = el.attr('data-id');

			var isAct = el.hasClass('act');
			var value = isAct ? data : null;

			el.siblings().removeClass('act');
			this.fire('radioFilter', value);
			return false;
		}
	});
	exports.resultFilter = ResultFilter;

	exports.checkOpener = function(context)
	{
		var state = true;
		try
		{
			state = window.opener && window.opener.pubjs;
		}
		catch(e)
		{
			state = false;
		}
		return state;
	}

	// 处理资质Info的脏数据
	exports.processQualificationInfo = function(info)
	{
		// 过滤历史脏数据，可能存在一个渠道可能存在多个记录
		var map = {};
		var items = util.clone(info || []);
		util.each(items, function(item)
		{
			if (!item)
			{
				return ;
			}

			if (!map[item.ExchangeId])
			{
				map[item.ExchangeId] = item;
			}

			// 如果有重复的渠道数据，并且渠道信息的IsDeleted不为true
			if (!item.IsDeleted)
			{
				map[item.ExchangeId] = item;
			}
		});

		var data = [];
		util.each(map, function(item)
		{
			data.push(item);
		});
		return data;
	}

	// 加工url，处理路径，附上search
	function processUrl(url){
		var hash = window.location.hash;
		var index = hash.indexOf('?');
		if(index != -1){
			return url + hash.substring(index);
		}else{
			return url;
		}
	}
	exports.processUrl = processUrl;

	// 获取品牌版search参数
	function getBrandSearch(newParam){
		var aderId = util.getQueryString('aderId');
		var planId = util.getQueryString('planId');
		var campaignId = util.getQueryString('campaignId');
		var search = [];
		if(aderId){
			search.push('aderId=' + aderId);
		}
		if(planId){
			search.push('planId=' + planId);
		}
		if(campaignId){
			search.push('campaignId=' + campaignId);
		}

		if(util.isObject(newParam)){
			for(var i in newParam){
				search.push(i + '=' + newParam[i]);
			}
		}

		if(search.length){
			return '?'+search.join('&');
		}else{
			return '';
		}
	}
	exports.getBrandSearch = getBrandSearch;

	// 改变或替换url中search的参数值
	function changeUrlParam(key, value){
		var hash = window.location.hash;
		var re = key+'=([^&]*)';
		var replaceText = key+'='+value;
		if (hash.match(re)){
			var tmp = '/'+key+'=[^&]*/g';
			tmp = hash.replace(eval(tmp), replaceText);
			return (tmp);
		}else{
			if (hash.match('[\?]')){
				return hash+'&'+ replaceText;
			}else{
				return hash+'?'+replaceText;
			}
		}
		return hash+'\n'+key+'\n'+value;
	}
	exports.changeUrlParam = changeUrlParam;

	// 判断是否品牌版
	function isBrandVersion(){
		// return pubjs.getUserCurrent('Version') == 1;
		return true;
	}
	exports.isBrandVersion = isBrandVersion;


	exports.isUrl = function(url){
		// var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
		// + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
		// + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
		// + "|" // 允许IP和DOMAIN（域名）
		// + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
		// + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
		// + "[a-z]{2,6})" // first level domain- .com or .museum
		// + "(:[0-9]{1,4})?" // 端口- :80
		// + "((/?)|" // a slash isn't required if there is no file name
		// + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		// var re = new RegExp(strRegex);
		// return !!re.test(url);

		// return !!url.match(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g);

		return !!url.match(/^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$/);
	}
});